<template>
  <BoTable
    :columns="columns"
    :request="getAlarmStrategyList"
    ref="tableRef"
    row-key="ruleId"
    :row-selection="rowSelection"
    :show-index="true"
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onAdd"> 新增 </Button>
        <Button :disabled="!selectKeys?.length" @click="onDelete(null)"
          >删除</Button
        >
      </Space>
    </template>
  </BoTable>
  <FormModal :columns="items"> </FormModal>
</template>
<route lang="json">
{
  "name": "alarm-strategy",
  "meta": {
    "title": "告警策略"
  }
}
</route>
<script setup lang="tsx">
import { computed, ref } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { listToEnum, listToOption } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, Modal, Space, message } from 'ant-design-vue';
import {
  addAlarmStrategy,
  deletAlarmStrategy,
  getAlarmStrategyList,
  getRoleGroupSelectList,
  updateAlarmStrategy,
} from './api';

const dictArr = ['alarm_type', 'use_status', 'alarm_methods'];
const {
  alarmTypeEnum,
  alarmTypeOptions,
  useStatusEnum,
  useStatusOptions,
  alarmMethodsEnum,
  alarmMethodsOptions,
} = useDicts(dictArr);

const tableRef = ref();
const selectKeys = ref<any[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, all) {
      selectKeys.value = values;
    },
  };
});

// 获取通知组信息
const noticeGroupOptions = ref([]);
const noticeGroupEnum = ref({});

const fetchNoticeGroupList = async () => {
  const res: any = await getRoleGroupSelectList();
  noticeGroupOptions.value = listToOption(res.data, 'groupName', 'id');
  noticeGroupEnum.value = listToEnum(res.data, 'groupName', 'id');
};
fetchNoticeGroupList();

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '告警名称',
    dataIndex: 'ruleName',
  },
  {
    title: '告警类型',
    dataIndex: 'alarmType',
    valueType: 'status',
    valueEnum: alarmTypeEnum.value,
  },
  {
    title: '告警方式',
    dataIndex: 'noticeMethod',
    hideInSearch: true,
    customRender({ record }) {
      return record.noticeMethod
        .split(',')
        .map((item) => {
          return alarmMethodsEnum.value[item]?.text;
        })
        ?.join();
    },
  },
  {
    title: '通知组',
    dataIndex: 'noticeGroup',
    hideInSearch: true,
    customRender({ record }) {
      return record.noticeGroup
        .split(',')
        .map((item) => {
          return noticeGroupEnum.value[item]?.text;
        })
        ?.join();
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueType: 'status',
    valueEnum: useStatusEnum.value,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      {
        text: '详情',
        onClick(record) {
          onView(record);
        },
      },
      {
        text: '删除',
        onClick(record) {
          onDelete(record);
        },
      },
    ],
  },
]);

const items = computed<BoFormProps['columns']>(() => [
  {
    title: '告警配置',
    dataIndex: 'alarmConfig',
    valueType: 'input',
    colProps: {
      span: 24,
    },
    formItemRender() {
      return <div class='module-title'>告警配置</div>;
    },
  },
  {
    title: '告警名称',
    dataIndex: 'ruleName',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入告警名称',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入告警名称',
    },
  },
  {
    title: '告警类型',
    dataIndex: 'alarmType',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择告警类型',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择告警类型',
      options: alarmTypeOptions.value as any,
    },
  },
  {
    title: '启用状态',
    dataIndex: 'status',
    valueType: 'radio',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择启用状态',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择启用状态',
      options: useStatusOptions.value as any,
    },
  },
  {
    title: '通知方式配置',
    dataIndex: 'noticeConfig',
    valueType: 'input',
    colProps: {
      span: 24,
    },
    formItemRender() {
      return <div class='module-title'>通知方式配置</div>;
    },
  },
  {
    title: '通知组',
    dataIndex: 'noticeGroup',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择通知组',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择通知组',
      options: noticeGroupOptions.value,
      mode: 'multiple',
    },
  },
  {
    title: '通知方式',
    dataIndex: 'noticeMethod',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择通知方式',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      mode: 'multiple',
      placeholder: '请选择通知方式',
      options: alarmMethodsOptions.value,
    },
  },
]);

const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 2,
});

const onView = (record: any) => {
  const noticeMethod = record.noticeMethod?.split(',');
  const noticeGroup = record.noticeGroup
    ?.split(',')
    .map((item) => Number(item));

  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: {
      ...record,
      noticeMethod,
      noticeGroup,
    },
    request: async (params: any) => {
      const { noticeMethod, noticeGroup, ruleName, alarmType, ruleId } = params;
      const modifyParams = {
        ...params,
        noticeGroup: noticeGroup.join(),
        noticeMethod: noticeMethod.join(),
        ruleName,
        alarmType,
        ruleId,
      };
      await updateAlarmStrategy(modifyParams);
      tableRef.value.refresh();
    },
  });
};

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {
      status: '1',
    },
    request: async (params: any) => {
      const { noticeMethod, noticeGroup, ruleName, alarmType } = params;
      await addAlarmStrategy({
        ...params,
        noticeGroup: noticeGroup.join(),
        noticeMethod: noticeMethod.join(),
        ruleName,
        alarmType,
      });
      tableRef.value.refresh();
    },
  });
};

const onDelete = async (record) => {
  const ids = record ? record.ruleId : selectKeys.value.join();
  if (!ids) return message.info('请选择要删除的数据');
  Modal.confirm({
    title: '系统提示',
    content: `确定删除当前选中项数据吗?`,
    onOk: async () => {
      await deletAlarmStrategy(ids);
      message.success('操作成功');
      tableRef.value.refresh();
    },
  });
};
</script>

<style lang="scss" scoped>
.alarm-form {
  border: 1px solid #fff;
  padding: 20px 20px 34px 20px;
  .ant-input {
    width: 80px;
  }
  .ant-select {
    width: 120px;
  }
}
</style>
